﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.Configuration;
using SCRUM.Core.DAO;
using SCRUM.Core.BusinessObjects;
using System.Collections.Generic;
using System.Web;
using System.Collections.Specialized;

/// <summary>
/// Presentation of the dashboard
/// </summary>
public partial class DashboardLayout : System.Web.UI.UserControl
{
    /// <summary>
    /// Number of add-widget-links displayed per table row in edit section
    /// </summary>
    private const int widgetsPerLine = 5;

    /// <summary>
    /// Dashboard layout.
    /// </summary>
    private SCRUM.Core.BusinessObjects.DashboardLayout dashboard;

    /// <summary>
    /// Index of active tab
    /// </summary>
    private int activeTabIndex;

    /// <summary>
    /// whether to show tab options or not
    /// </summary>
    private bool haveToShowTabOptions = false;

    #region [DashboardLayout]

    /// <summary>
    /// Initializes a new instance of the <see cref="DashboardLayout"/> class.
    /// </summary>
    public DashboardLayout()
    {
        dashboard = new SCRUM.Core.BusinessObjects.DashboardLayout();
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        NameValueCollection parameters = Request.QueryString;
        if (string.IsNullOrEmpty(parameters["tabId"]))
        {
            activeTabIndex = DAOWidgetTab.GetActiveTab().Order;
        }
        else
        {
            Int32.TryParse(Request.QueryString["tabId"], out activeTabIndex);
        }
        if (activeTabIndex == -1)
        {
            string newName = Request.QueryString["tabName"];
            newName = newName == null ? TextBoxNewTabName.Text:newName;
            int widgetTypeID;
            if (Int32.TryParse(Request.QueryString["widgetTypeID"], out widgetTypeID))
            {
                CreateTab(newName, widgetTypeID);
            }
            activeTabIndex = 0;
        }
        //this.RenderLayout(activeTabIndex);
        RenderLayout(activeTabIndex);
    }

    /// <summary>
    /// Goes to tab with specified index
    /// </summary>
    /// <param name="tabIndex">Index of the tab.</param>
    public void SelectActiveTab(int tabIndex)
    {
        Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
    }

    /// <summary>
    /// Creates the tab with newName eventually with new widget on it
    /// </summary>
    /// <param name="newName">The new name.</param>
    /// <param name="widgetID">The widget ID.</param>
    /// <returns>true if success</returns>
    private bool CreateTab(string newName, int widgetID)
    {
        if (newName == string.Empty)
        {
            return false;
        }
        TextBoxNewTabName.Text = "";
        int pred = dashboard.Tabs.Count;
        DAOWidgetTab.AddTab(newName);
        int po = dashboard.Tabs.Count;
        if (widgetID != -1) AddWidgetToTab(widgetID, 0);
        SelectActiveTab(dashboard.Tabs.Count);
        return true;
    }

    /// <summary>
    /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
    /// </summary>
    /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
    //protected override void OnPreRender(EventArgs e)
    //{
    //    base.OnPreRender(e);
    //    //this.PanelItemDetails.Visible = this.haveToShowItemDetails;
    //    //this.DataSection.Visible = this.haveToShowDataSection;
    //    //this.PanelTabOptions.Visible = this.haveToShowTabOptions;
    //    RenderLayout(activeTabIndex);
    //}

    /// <summary>
    /// Renders the layout of the dashboard.
    /// </summary>
    /// <param name="activeTabIndex">Index of the active tab.</param>
    protected void RenderLayout(int activeTabIndex)
    {
        WidgetTab activeTab;
        if (String.IsNullOrEmpty(Request.QueryString["tabId"]))
        {
            activeTab = DAOWidgetTab.GetActiveTab();
            activeTabIndex = activeTab.Order;
        }
        else
        {
            //if (activeTabIndex == this.dashboard.Tabs.Count)
            //{
            //    --activeTabIndex;
            //}
            activeTab = this.dashboard.Tabs[activeTabIndex];
            DAOWidgetTab.SetActive(activeTab);
        }

        // Render tab headers
        RenderTabHeaders(activeTabIndex);

        // Render tab options
        RenderTabOptions(activeTab);

        // Render active tab
        RenderActiveTab(activeTab);
    }
    #endregion

    #region [Tab Headers]

    /// <summary>
    /// Renders the tab headers.
    /// </summary>
    /// <param name="activeTabIndex">Index of the active tab.</param>
    private void RenderTabHeaders(int activeTabIndex)
    {
        PanelTabHeaders.Controls.Clear();
        for (int i = 0; i < this.dashboard.Tabs.Count; i++)
        {
            Panel panel = GetTabHeader(activeTabIndex, i);
            PanelTabHeaders.Controls.Add(panel);
        }       
    }

    /// <summary>
    /// Gets the tab header code.
    /// </summary>
    /// <param name="activeTabIndex">Index of the active tab.</param>
    /// <param name="order">The order.</param>
    /// <returns></returns>
    private Panel GetTabHeader(int activeTabIndex, int order)
    {
        bool active = activeTabIndex == order;
        Panel panel = new Panel();
        panel.CssClass = active? "TabHeader-Active" : "TabHeader";
        
        if (active)
        {
            // nadpis tabu
            Literal literal = new Literal();
            literal.Text = this.dashboard.Tabs[order].Name;
            panel.Controls.Add(literal);

            // button na edit tabu
            ImageButton ImageButtonTabMenu = new ImageButton();
            ImageButtonTabMenu.ImageUrl = "~/Resources/Pictures/pencil2.png";
            ImageButtonTabMenu.Style.Add("margin-left", "4px");
            ImageButtonTabMenu.CssClass = "NewTabButton";
            ImageButtonTabMenu.Click += new ImageClickEventHandler(ImageButtonTabMenu_Click);
            ImageButtonTabMenu.ToolTip = (string)GetLocalResourceObject("EditTabDescription");
            panel.Controls.Add(ImageButtonTabMenu);

            this.ConfirmButtonExtenderDeleteActiveTab.ConfirmText = String.Format((string)GetLocalResourceObject("ConfirmDeletingTab"), this.dashboard.Tabs[order].Name);
        }
        else
        {
            // link na neaktivny tab
            HyperLink link = new HyperLink();
            link.Text = this.dashboard.Tabs[order].Name;
            link.NavigateUrl = "~/Default.aspx?tabId=" + order.ToString();
            panel.Controls.Add(link);
        }

        //image na zavretie
        ImageButton ImageButtonCloseTab = new ImageButton();
        ImageButtonCloseTab.ID = "CloseTab" + order.ToString();
        ImageButtonCloseTab.ImageUrl = "~/Resources/Pictures/close1_light.png";
        ImageButtonCloseTab.CssClass = "CloseTabButton";
        ImageButtonCloseTab.Command += new CommandEventHandler(ImageButtonCloseTab_Command);
        ImageButtonCloseTab.CommandArgument = order.ToString();
        ImageButtonCloseTab.ToolTip = (string)GetLocalResourceObject("CloseTabDescription");
        panel.Controls.Add(ImageButtonCloseTab);

        AjaxControlToolkit.ConfirmButtonExtender confirmer = new AjaxControlToolkit.ConfirmButtonExtender();
        confirmer.TargetControlID = ImageButtonCloseTab.ID;
        confirmer.ConfirmText = String.Format((string)GetLocalResourceObject("ConfirmDeletingTab"), this.dashboard.Tabs[order].Name);
        panel.Controls.Add(confirmer);
        //TextBoxTabName.
        //ButtonChangeTabName.Focus();
        return panel;
    }

    /// <summary>
    /// Handles the Click event of the ImageButtonTabMenu control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
    void ImageButtonTabMenu_Click(object sender, ImageClickEventArgs e)
    {
        this.PanelTabOptions.Visible = true;
        this.UP.Update();
    }

    /// <summary>
    /// User tries to close some tab with little button in tab header
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    void ImageButtonCloseTab_Command(object sender, CommandEventArgs e)
    {
        int tab = Int32.Parse((string)e.CommandArgument);
        DeleteTab(tab);
    }

    /// <summary>
    /// Handles the Click event of the ButtonCreateNewTab control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonCreateNewTab_Click(object sender, EventArgs e)
    {
        if (CreateTab(TextBoxNewTabName.Text, -1))
        {
            SelectActiveTab(this.dashboard.Tabs.Count);
        }
    }
    #endregion

    #region [Tab Options]
    /// <summary>
    /// Renders the tab options area/panel.
    /// </summary>
    /// <param name="tab">The active tab.</param>
    private void RenderTabOptions(WidgetTab activeTab)
    {        
        // nova a cista stranka -> spustime edit
        if (TabIsEmpty(activeTab))
        {
            ShowOptions();
        }

        // na prvy load
        if (!IsPostBack)
        {
            // Tab
            TextBoxTabName.Text = this.dashboard.ActiveTab.Name;
        }   
    }

    /// <summary>
    /// Shows the options/edit area of dashboard
    /// </summary>
    private void ShowOptions()
    {
        PanelTabOptions.Visible = true;
        this.haveToShowTabOptions = true;
    }

    /// <summary>
    /// Returns whether Tab is empty.
    /// </summary>
    /// <param name="tab">The active tab.</param>
    /// <returns></returns>
    private static bool TabIsEmpty(WidgetTab tab)
    {
        return tab.Columns.Count == 0 || tab.Columns[0].Widgets.Count == 0;
    }

    /// <summary>
    /// Handles the Click event of the ButtonChangeTabName control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonChangeTabName_Click(object sender, EventArgs e)
    {
        dashboard.ActiveTab.Name = TextBoxTabName.Text;
        DAOWidgetTab.Rename(dashboard.ActiveTab);
        SelectActiveTab(activeTabIndex);
    }

    /// <summary>
    /// Adds new Instance of widget with specified widgetType
    /// </summary>
    /// <param name="widgetID">The widget ID.</param>
    private void AddWidgetToTab(int widgetTypeID, int column)
    {
        //Widget widget = new Widget();
        //widget.TypeID = widgetTypeID;
        //widget.Order = 0;
        DAOWidget.CreateNewWidget(widgetTypeID, 0, this.dashboard.ActiveTab.Columns[column].ID);
    }

    /// <summary>
    /// Handles the Click event of the ButtonSaveTabSettings control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonHideTabSettings_Click(object sender, EventArgs e)
    {
        PanelTabOptions.Visible = false;
        this.UP.Update();
    }

    /// <summary>
    /// Handles the Click event of the ButtonDeleteActiveTab control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonDeleteActiveTab_Click(object sender, EventArgs e)
    {
        DeleteTab(activeTabIndex);
    }

    private void DeleteTab(int tabIndex)
    {
        if (dashboard.Tabs.Count == 1)
        {
            return;
        }
        int newActiveTabIndex;
        if (activeTabIndex == tabIndex)
        {
            // najdem najblizsi tab ktory oznacim ako aktivny
            newActiveTabIndex = activeTabIndex==0 ? activeTabIndex : activeTabIndex-1;//activeTabIndex % (dashboard.Tabs.Count - 1);
        }
        else
        {
            newActiveTabIndex = activeTabIndex;
        }
        // zmazem tab
        DAOWidgetTab.DeleteTab(this.dashboard.Tabs[tabIndex]);
        //upravim poradie tabov
        DAOWidgetTab.FixOrder(dashboard.Tabs[tabIndex].UserID, tabIndex);
        // nastavim aktivny
        Response.Redirect("~/Default.aspx?tabId=" + newActiveTabIndex.ToString());
    }
    #endregion

    #region [Tab Content]
    /// <summary>
    /// Renders the active tab.
    /// </summary>
    /// <param name="tab">The active tab.</param>
    private void RenderActiveTab(WidgetTab activeTab)
    {
        PanelTab.Controls.Clear();
        Panel panelTab = new Panel();
        panelTab.CssClass = "Tab";
        decimal columnWidth;
        decimal tabColumnsCount = (decimal)(activeTab.Columns.Count);
        if(tabColumnsCount != 0)
        {
            columnWidth = Math.Floor((100 / tabColumnsCount)-1);
        }
        else
        {
            columnWidth = 100;
        }

        Panel panelColumn = new Panel(); 
            panelColumn.Style.Add(HtmlTextWriterStyle.Width, String.Format("{0}%", columnWidth.ToString()));
            panelColumn.Style.Add("min-width", String.Format("{0}px", ConfigManager.CurrentConfig.Widgets.MinimalWidth));
            panelColumn.Attributes.Add("class", "tabColumn");

        foreach (WidgetColumn column in activeTab.Columns)
        {
            Column col = LoadControl("~/User Controls/Dashboard/Column.ascx") as Column;
            col.column = column;
            col.columnWidth = columnWidth;
            col.parent = activeTab;
            col.tabIndex = activeTabIndex;
            col.createColumn();
            panelTab.Controls.Add(col);
        } 
        PanelTab.Controls.Add(panelTab);
    }
    #endregion
}

